import {
  savePromotionProject,
  savePromotionProjectTreeAssignOrganization,
  sendPromotionProjectTemplateMessage,
} from '@/services/api/api-promotion';
import {
  CloseOutlined,
  ExclamationCircleOutlined,
  FolderOutlined,
  HomeOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import ProForm, {
  DrawerForm,
  ProFormDateTimeRangePicker,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import ProList from '@ant-design/pro-list';
import { ActionType } from '@ant-design/pro-table';
import {
  Button,
  Descriptions,
  Divider,
  Empty,
  Modal,
  Popconfirm,
  Space,
  Tag,
  Typography,
  message,
} from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import 'dayjs/locale/zh-cn';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import AddTaskDouyin from './add/AddTaskDouyin';
import AddTaskGongzhonghao from './add/AddTaskGongzhonghao';
import AddTaskShipinhao from './add/AddTaskShipinhao';
import EditTaskDouyin from './edit/EditTaskDouyin';
import EditTaskGongzhonghao from './edit/EditTaskGongzhonghao';
import EditTaskShipinhao from './edit/EditTaskShipinhao';

interface AddPromotionProjectProps {
  onRefurbish: (id: string) => void;
}

const AddPromotionProject: React.FC<AddPromotionProjectProps> = ({ onRefurbish }) => {
  /**
   * 强制刷新
   */
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);

  //选题计划
  const [tasks, setTasksState] = useState<PromotionTaskBo.TaskBo[]>([]);

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  /**
   * 初始化树形数据
   */
  const [treeOrganizationData, setTreeOrganizationDataState] = useState<DataNode[]>();
  /**
   * 树形列表选择数据
   */
  const [checkedOrganizationIds, setCheckedOrganizationIdsState] = useState<any[]>([]);

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <HomeOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载组织详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await savePromotionProjectTreeAssignOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setTreeOrganizationDataState(treeData);
      }
    } catch (error) { }
  };

  const description = (row: PromotionTaskBo.TaskBo) => {
    const type = row?.type;

    if (type === 1) {
      return (
        <>
          <Typography.Paragraph>
            <blockquote>{row?.route}</blockquote>
          </Typography.Paragraph>
          <Descriptions>
            <Descriptions.Item label="阅读时长（秒）">{row?.isDemandReadTime}</Descriptions.Item>
            <Descriptions.Item label="是否分享">
              {row?.isDemandShare === 0 ? '否' : '是'}
            </Descriptions.Item>
            {row?.isDemandShare === 1 && (
              <Descriptions.Item label="分享后是否需要第三方阅读">
                {row?.isDemandShareRead === 0 ? '否' : '是'}
              </Descriptions.Item>
            )}
          </Descriptions>
          {row?.remarks !== undefined && (
            <Descriptions>
              <Descriptions.Item label="备注">{row?.remarks}</Descriptions.Item>
            </Descriptions>
          )}
        </>
      );
    } else if (type === 2) {
      return (
        <>
          <Typography.Paragraph>
            <blockquote>{row?.routeFinderUserName}</blockquote>
          </Typography.Paragraph>
          <Typography.Paragraph>
            <blockquote>{row?.routeFeedId}</blockquote>
          </Typography.Paragraph>
          {row?.remarks !== undefined && (
            <Descriptions>
              <Descriptions.Item label="备注">{row?.remarks}</Descriptions.Item>
            </Descriptions>
          )}
        </>
      );
    } else if (type === 3) {
      return (
        <>
          <Typography.Paragraph>
            <blockquote>{row?.route}</blockquote>
          </Typography.Paragraph>
          <Descriptions>
            <Descriptions.Item label="是否复制到剪贴板">
              {row?.isDemandShare === 0 ? '否' : '是'}
            </Descriptions.Item>
          </Descriptions>
          {row?.remarks !== undefined && (
            <Descriptions>
              <Descriptions.Item label="备注">{row?.remarks}</Descriptions.Item>
            </Descriptions>
          )}
        </>
      );
    }

    return <></>;
  };

  return (
    <DrawerForm
      key="add_promotion_project_drawer_form"
      title="新建任务"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      initialValues={{
        deadline: [Date.now(), ],
      }}
      formRef={formRef}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建任务
        </Button>
      }
      onOpenChange={(visible: boolean) => {
        if (visible) {
          //加载权限树请求网络
          loadOrganizationData();
        } else {
          setCheckedOrganizationIdsState([]);
        }
      }}
      onFinish={async (values) => {
        if (tasks.length === 0) {
          message.warning('请添加至少一个任务');
          return false;
        }

        let deadline = '';
        if (values.deadline !== undefined && values.deadline.length === 2) {
          deadline = values.deadline[1];
        }

        let isAssign: number = 0;
        if (
          values.assignOrganizationNames !== undefined &&
          values.assignOrganizationNames.length > 0
        ) {
          isAssign = 1;
          const checkNames = formRef.current?.getFieldValue('assignOrganizationNames') as [];
          if (checkNames) {
            const checkOrgs = new Array();
            checkedOrganizationIds?.forEach((item) => {
              if (checkNames.includes(item?.name)) {
                checkOrgs.push(item);
              }
            });
            values.assignOrganizationIds = Array.from(checkOrgs, ({ id }) => id);
          }
        }

        const response = await savePromotionProject({
          ...values,
          deadline,
          isAssign,
          tasks,
        });

        if (response.code === 0) {
          setTasksState([]);
          onRefurbish(response.data);
          message.success('提交成功');
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormDateTimeRangePicker
          rules={[{ required: true, message: '这是必填项' }]}
          width="xl"
          name="deadline"
          label="任务执行截止时间"
          tooltip="到达截止时候后，系统关闭单位任务渠道"
          fieldProps={{
            disabled: [true, false],
            ranges: {
              后5天: [moment(), moment().add(5, 'days')],
              后10天: [moment(), moment().add(10, 'days')],
              后15天: [moment(), moment().add(15, 'days')],
              后20天: [moment(), moment().add(20, 'days')],
            },
            format: 'YYYY-MM-DD HH:mm:ss',
          }}
        />
        <ProFormText
          width="xl"
          name="name"
          label="标题"
          tooltip="不填写会自动生成的"
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
        />
        <ProFormTextArea
          width="xl"
          name="remarks"
          label="备注"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 200,
          }}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          name="assignOrganizationNames"
          label="指派单位（不选择，默认推送给所有部门）"
          showSearch
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            showSearch: true,
            showArrow: false,
            open: false,
            optionFilterProp: 'children',
            filterOption: (input: any, option: any) => {
              console.log(option);
              // return option.options.filter((item: any) => item.label.includes(input));
              return option.label.includes(input);
            },
            listHeight: 500,
            style: {
              width: 488,
            },
          }}
          addonAfter={
            <DrawerForm
              width="500px"
              title="推送范围：自定义（多选）"
              trigger={<a key="activeSaveAssign">点击添加</a>}
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
              }}
              onVisibleChange={(visible: boolean) => {
                if (visible) {
                  const checkNames = formRef.current?.getFieldValue(
                    'assignOrganizationNames',
                  ) as [];
                  if (checkNames) {
                    const checkOrgs = new Array();
                    checkedOrganizationIds?.forEach((item) => {
                      if (checkNames.includes(item?.name)) {
                        checkOrgs.push(item);
                      }
                    });
                    setCheckedOrganizationIdsState(checkOrgs);
                  }
                }
              }}
              submitter={false}
            >
              {treeOrganizationData && treeOrganizationData.length ? (
                <Tree
                  defaultExpandAll
                  showLine={{ showLeafIcon: false }}
                  showIcon={true}
                  treeData={treeOrganizationData}
                  checkedKeys={checkedOrganizationIds.map((item) => {
                    return item.id;
                  })}
                  checkable
                  onCheck={(checkedKeys, e) => {
                    const checkOrgs = new Array();

                    e.checkedNodesPositions?.forEach((item) => {
                      if (item.node?.item?.isFolder === 0) {
                        checkOrgs.push(item.node.item);
                      }
                    });

                    setCheckedOrganizationIdsState(checkOrgs);

                    formRef.current?.setFieldsValue({
                      assignOrganizationNames: Array.from(checkOrgs, ({ name }) => name),
                    });
                  }}
                />
              ) : (
                <Empty />
              )}
            </DrawerForm>
          }
        />
      </ProForm.Group>
      <Divider orientation="left" plain>
        添加任务
      </Divider>
      <div style={{ textAlign: 'right' }}>
        <Space align="center">
          <PlusOutlined />
          <AddTaskGongzhonghao
            key={'add_promotion_task_gongzhonghao'}
            onRefurbish={(task: PromotionTaskBo.TaskBo) => {
              tasks?.push(task);
              setTasksState(tasks);
              console.log('======', task.type, task, tasks);
              actionRef.current?.reset();
            }}
          />
          <AddTaskShipinhao
            key={'add_promotion_task_shipinhao'}
            onRefurbish={(task: PromotionTaskBo.TaskBo) => {
              tasks?.push(task);
              setTasksState(tasks);
              console.log('======', task.type, task, tasks);
              actionRef.current?.reset();
            }}
          />
          <AddTaskDouyin
            key={'add_promotion_task_douyin'}
            onRefurbish={(task: PromotionTaskBo.TaskBo) => {
              tasks?.push(task);
              setTasksState(tasks);
              console.log('======', task.type, task, tasks);
              actionRef.current?.reset();
            }}
          />
        </Space>
      </div>
      <ProList<PromotionTaskBo.TaskBo>
        toolBarRender={false}
        rowKey="id"
        showActions="always"
        actionRef={actionRef}
        dataSource={tasks}
        itemCardProps={{
          style: {
            padding: 12,
          },
          bodyStyle: {
            padding: 12,
          },
        }}
        onDataSourceChange={setTasksState}
        metas={{
          title: {
            dataIndex: 'name',
            render: (dom: React.ReactNode, entity) => {
              return (
                <Space
                  align="center"
                  style={{
                    paddingLeft: 12,
                    paddingRight: 12,
                  }}
                >
                  <Tag
                    style={{
                      display: 'flex',
                      padding: 5,
                    }}
                  >
                    <img
                      width={22.4}
                      style={{
                        margin: 'auto 2px',
                      }}
                      src={entity.logo}
                    />
                    <span>{entity.typeName}</span>
                  </Tag>
                  <span
                    style={{
                      fontSize: 16,
                      fontWeight: 'bold',
                    }}
                  >
                    {entity.name}
                  </span>
                </Space>
              );
            },
          },
          description: {
            render: (dom: React.ReactNode, entity) => {
              return (
                <div
                  style={{
                    width: '100%',
                    paddingLeft: 12,
                    paddingRight: 12,
                  }}
                >
                  {description(entity)}
                </div>
              );
            },
          },
          content: {},
          actions: {
            render: (text, row, index) => [
              row.type === 1 ? (
                <EditTaskGongzhonghao
                  key={'edit_promotion_task_gongzhonghao'}
                  task={row}
                  onRefurbish={(task: PromotionTaskBo.TaskBo) => {
                    tasks.forEach((item) => {
                      if (item.id === task.id) {
                        item.name = task.name;
                        item.route = task.route;
                        item.remarks = task.remarks;
                        item.isDemandReadTime = task.isDemandReadTime;
                        item.isDemandShare = task.isDemandShare;
                        item.isDemandShareRead = task.isDemandShareRead;
                      }
                    });
                    setTasksState(tasks);
                    forceUpdate();
                  }}
                />
              ) : row.type === 2 ? (
                <EditTaskShipinhao
                  key={'edit_promotion_task_shipinhao'}
                  task={row}
                  onRefurbish={(task: PromotionTaskBo.TaskBo) => {
                    tasks.forEach((item) => {
                      if (item.id === task.id) {
                        item.name = task.name;
                        item.routeFinderUserName = task.routeFinderUserName;
                        item.routeFinderUserName = task.routeFinderUserName;
                        item.remarks = task.remarks;
                      }
                    });
                    setTasksState(tasks);
                    forceUpdate();
                  }}
                />
              ) : (
                <EditTaskDouyin
                  key={'edit_promotion_task_douyin'}
                  task={row}
                  onRefurbish={(task: PromotionTaskBo.TaskBo) => {
                    tasks.forEach((item) => {
                      if (item.id === task.id) {
                        item.name = task.name;
                        item.route = task.route;
                        item.remarks = task.remarks;
                        item.isDemandClipboard = task.isDemandClipboard;
                      }
                    });
                    setTasksState(tasks);
                    forceUpdate();
                  }}
                />
              ),
              <Popconfirm
                key={row.id + index + 'popconfirm'}
                title="提示"
                description="是否要删除该任务"
                onConfirm={() => {
                  const list = tasks.filter((item) => item.id !== row.id);

                  setTasksState(list);
                  forceUpdate();
                }}
                okText="是"
                cancelText="否"
              >
                <a key={row.id + index + 'a'}>删除</a>
              </Popconfirm>,
            ],
          },
        }}
      />
    </DrawerForm>
  );
};
export default AddPromotionProject;
